package com.fingerth.demo.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Looper
import android.view.Gravity
import android.widget.Toast
import java.lang.ref.WeakReference


object ToastUtils {
    private var wToast: WeakReference<Toast>? = null

    fun showToast(context: Context, msg: String, duration: Int = Toast.LENGTH_SHORT) {
        if (Looper.getMainLooper().thread == Thread.currentThread()) {
            doToast(context, msg, duration)
        } else {
            if (context is Activity) context.runOnUiThread { doToast(context, msg, duration) }
        }
    }

    @SuppressLint("ShowToast")
    private fun doToast(context: Context, msg: String, duration: Int) {
        if (wToast?.get() == null) wToast = WeakReference(Toast.makeText(context, "", duration))
        wToast?.get()?.let {
            it.setText(msg)
            it.show()
        }

    }

    fun showNetError(context: Context) = showToast(context, "网络错误!")
}